<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
// import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
// import { reactive, ref } from 'vue'

import { snapshotSave, snapshotDel, snapshotList, sourceDel, sourceSave, sourceList, sourceEnable, sourceMove, getHouseList, useBaozuList } from '@fl/api/advertising-api/goods-group'

import { SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { defineProps } from 'vue'

import { adgDialogTag } from '../type'
import { useDicts } from '../hooks/use-dicts'

const props = withDefaults(defineProps<{
    modelValue: number
}>(), {
    modelValue: 1,
})

const timeList = ref()
const currentTime = ref(0)
const loading = ref(false)
const btnLoading = ref(false)
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const list = ref([])
const isLoading = ref(false)
const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'plate', slots: { default: 'plate' }, title: '业务类型' },
        { field: 'projectName', title: '楼盘/产品名称' },
        { field: 'activeStatus', slots: { default: 'activeStatus' }, title: '启用/禁用', width: 90 },
        { fixed: 'right', slots: { default: 'operate' }, title: '操作', width: 300 },
    ],
})
const initForm = {
    activeEnd: '', // 生效结束时间
    activeStart: '', // 生效开始时间
    groupSnapshotId: undefined, // 商品排期id
    id: undefined, // 商品id
    sort: undefined,
    projectName: '', // 商品名称
    plate: '', // 业务类型
}

const adForm = ref(cloneDeep(initForm))
const dialogTitle = ref('')
const dialogVisible = ref(false)
const reqjson = ref([])
const adFormRef = ref()
const dialogWidth = ref(666)
const { dicts: { PlateType }, useDict } = useDicts()
const projectOptions = ref()
const projectObj = ref() // 选择楼盘后带出来的信息
watch(
    () => props.modelValue,
    () => {
        getTimeList()
    },
    { immediate: true },
)

const houseOptions = ref()
const baozuOptions = ref()
const isTrue = ref<boolean>(true)
const { data: baozuList } = useBaozuList(isTrue)

// 好房列表(新)
function getHouseOptions() {
    getHouseList().then((res) => {
        houseOptions.value = cloneDeep(res.rows).reduce((pre, cur) => {
            cur.value = cur.projectId
            cur.label = cur.projectName
            pre.push(cur)
            return pre
        }, [])
    })
}

getHouseOptions()

watchEffect(() => {
    if(baozuList.value) {
        baozuOptions.value = cloneDeep(baozuList.value.rows).reduce((pre, cur) => {
            cur.value = cur.id
            cur.label = cur.goodsName
            pre.push(cur)
            return pre
        }, [])
    }
    if(adForm.value.plate === '2') {
        projectOptions.value = baozuOptions.value 
    } else if(adForm.value.plate === '1') {
        projectOptions.value = houseOptions.value 
    } else {
        projectOptions.value = []
    }
})

/**
 * methods start
 */

// 获取分期列表以及默认选中第一条
function getTimeList() {
    loading.value = true
    snapshotList({
        id: props.modelValue,
    }).then((data) => {
        loading.value = false
        // data有数据说明已存在商品排期
        if (data.length) {
            timeList.value = data.map(item => ({
                ...item,
                activeTime: [item.activeStart, item.activeEnd],
            }))
            selectTime(0, timeList.value[0])
        }
        else {
            timeList.value = [{
                activeTime: [],
                groupId: props.modelValue,
            }]
        }
    }).catch(() => {
        loading.value = false
    })
}

// 新增分期
function addAdTime(item, index) {
    const time = cloneDeep({
        activeTime: [],
        groupId: props.modelValue,
    })
    timeList.value.push(time)
    selectTime(index + 1, time)
}

// 获取分期下的商品列表
function getGoodsList(id) {
    isLoading.value = true
    sourceList({
        snapshotId: id,
        pageNum: tablePage.value.currentPage,
        pageSize: tablePage.value.pageSize,
    }).then((res) => {
        isLoading.value = false
        // 考虑非第一页刚好只有一条被删除的情况
        if (tablePage.value.currentPage !== 1 && !res.rows?.length) {
            tablePage.value.currentPage--
            getGoodsList(id)
            return
        }
        list.value = res.rows.reduce((pre,cur) => {
            cur.activeStatus = cur.activeStatus ?? 0
            cur.plate = String(cur.plate)
            pre.push(cur)
            return pre
        }, [])
        tablePage.value.total = res.total
    }).catch(() => {
        isLoading.value = false
    })
}

// 选择分期
function selectTime(index, item) {
    currentTime.value = index
    adForm.value.groupSnapshotId = item.id
    if (item.activeStart && item.activeEnd) {
        adForm.value.activeStart = item.activeStart
        adForm.value.activeEnd = item.activeEnd
    }
    else {
        list.value = []
    }
    item.id && getGoodsList(item.id)
}

// 设置分期时间
async function changeTime(val, item, index) {
    if (val) {
        if (item.activeEnd && item.activeStart) {
            await snapshotSave({
                activeEnd: val[1],
                activeStart: val[0],
                groupId: props.modelValue,
                id: item.id,
            }).then((res) => {
                item.activeTime = [res.activeStart, res.activeEnd]
                item.activeStart = res.activeStart
                item.activeEnd = res.activeEnd
                item.id = res.id
            }).catch(() => {
                item.activeTime = []
            })
            selectTime(index, item)
        }
        else {
            await snapshotSave({
                activeEnd: val[1],
                activeStart: val[0],
                groupId: props.modelValue,
            }).then((res) => {
                item.activeTime = [res.activeStart, res.activeEnd]
                item.activeStart = res.activeStart
                item.activeEnd = res.activeEnd
                item.id = res.id
                selectTime(index, item)
            }).catch(() => {
                item.activeTime = []
            })
        }
    }
}

// 删除分期
function delTime(item, index) {
    if (item.activeTime?.length) {
        ElMessageBox.confirm(
            '您确认要删除这个商品排期吗',
            '删除',
            {
                cancelButtonText: '取消',
                confirmButtonText: '删除',
                type: 'warning',
            },
        )
            .then(() => {
                snapshotDel({
                    activeEnd: item.activeTime[1],
                    activeStart: item.activeTime[0],
                    groupId: props.modelValue,
                    id: item.id,
                }).then(() => {
                    timeList.value.splice(index, 1)
                    let currentKey = 0
                    if (currentTime.value === index) {
                        if (index !== timeList.value.length)
                            currentKey = index
                        selectTime(currentKey, timeList.value[currentKey])
                    }
                    ElMessage({
                        message: '删除成功',
                        type: 'success',
                    })
                })
            }).catch(() => {
                ElMessage({
                    message: '取消删除',
                    type: 'info',
                })
            })
    }
    else {
        timeList.value.splice(index, 1)
        let currentKey = 0
        if (currentTime.value === index) {
            if (index !== timeList.value.length)
                currentKey = index
            selectTime(currentKey, timeList.value[currentKey])
        }
    }
}

// 分页
const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    getGoodsList(adForm.value.groupSnapshotId)
}

// 添加商品
async function addAdvertising() {
    dialogTitle.value = adgDialogTag.ADD_ADVERTISING
    const newForm = {
        activeEnd: adForm.value.activeEnd,
        activeStart: adForm.value.activeStart,
        groupSnapshotId: adForm.value.groupSnapshotId,
        id: undefined,
        sort: undefined,
        projectName: '',
        plate: ''
    }
    reqjson.value = []
    adForm.value = newForm
    adFormRef.value?.resetFields()
    dialogVisible.value = true
}

// 提交商品
async function advertisingSbumit(formEl: FormInstance | undefined) {
    if (dialogTitle.value === adgDialogTag.SELECT_MATERIAL) {
        dialogTitle.value = adForm.value.id ? adgDialogTag.EDIT_ADVERTISING : adgDialogTag.ADD_ADVERTISING
        dialogWidth.value = 666
    }
    else {
        if (!formEl)
            return
        await formEl.validate(async (valid, fields) => {
            if (valid) {
                let msg = ''
                const { activeEnd, activeStart, groupSnapshotId, id, sort, projectName, plate } = adForm.value
                const params = {
                    activeEnd,
                    activeStart,
                    groupSnapshotId,
                    id,
                    sort: sort ?? tablePage.value.total + 1,
                    projectName,
                    plate,
                    cooperationType: plate === '2' ? 'hezlxId' : '', // 保租多加一个字段
                    ...unref(projectObj)
                }

                if (id) {
                    btnLoading.value = true
                    await sourceSave(params).then(() => {
                        msg = '编辑成功'
                    }).catch(() => {
                        btnLoading.value = false
                    })
                }
                else {
                    btnLoading.value = true
                    await sourceSave(params).then(() => {
                        msg = '添加成功'
                    }).catch(() => {
                        btnLoading.value = false
                    })
                }
                if (msg) {
                    ElMessage({
                        message: msg,
                        type: 'success',
                    })
                    getGoodsList(groupSnapshotId)
                    dialogVisible.value = false
                }
                btnLoading.value = false
            }
            else {
                console.log('error submit!', fields)
            }
        })
    }
}

// 弹窗关闭前
function beforeClose() {
    if (dialogTitle.value === adgDialogTag.SELECT_MATERIAL) {
        dialogTitle.value = adForm.value.id ? adgDialogTag.EDIT_ADVERTISING : adgDialogTag.ADD_ADVERTISING
        dialogWidth.value = 666
        // adForm.value[selectType.value] = ''
    }
    else {
        dialogVisible.value = false
    }
}

// 启用禁用
function switchActiveStatus(row) {
    const params = {
        enable: row.activeStatus,
        id: row.id,
    }
    sourceEnable(params).then(() => {
        const tips = row.activeStatus === 1 ? '已启用' : '已禁用'
        ElMessage({
            message: tips,
            type: row.activeStatus === 1 ? 'success' : 'info',
        })
        getGoodsList(row.groupSnapshotId)
    })
}

// 上移、下移、置顶、置底
function moveItem(row, type) {
    const { groupSnapshotId, id } = row
    // 1置顶 2上移 3下移 4置底
    sourceMove({
        id,
        move: type
    }).then(() => {
        getGoodsList(groupSnapshotId)
        ElMessage({
            message: '操作成功',
            type: 'success',
        })
    })
}

// 删除商品
function delAdvertising(row) {
    const { id, projectName } = row
    ElMessageBox.confirm(
        `您确认要删除商品『${projectName}』吗`,
        '删除',
        {
            cancelButtonText: '取消',
            confirmButtonText: '删除',
            type: 'warning',
        },
    )
        .then(() => {
            sourceDel({
                id,
            }).then(() => {
                getGoodsList(row.groupSnapshotId)
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
            })
        }).catch(() => {
            ElMessage({
                message: '取消删除',
                type: 'info',
            })
        })
}

// 编辑商品
async function editAdItem(row) {
    dialogTitle.value = adgDialogTag.EDIT_ADVERTISING
    adForm.value = cloneDeep(row)
    dialogVisible.value = true
}

// 选择楼盘/产品
function projectChange(val) {
    const item = projectOptions.value.find(item => item.value === val)
    projectObj.value = {
        projectId: item.value,
        projectName: item.label,
    }
}

/**
 * methods end
 */
</script>

<template>
    <div class="ad-config">
        <el-skeleton v-if="loading" :rows="5" animated />

        <div v-else class="content">
            <div class="ad-by-stages">
                <div v-for="(item, index) in timeList" :key="item.adTime" class="time-item">
                    <div :class="currentTime === index ? 'ad-time-piker active' : 'ad-time-piker'">
                        <el-date-picker v-model="item.activeTime" type="datetimerange" start-placeholder="开始日期"
                            end-placeholder="结束日期" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                            @change="(val) => changeTime(val, item, index)" />

                        <span :class="currentTime === index ? 'sort active' : 'sort'" @click="selectTime(index, item)">
                            {{ index + 1 }}
                        </span>
                    </div>

                    <div class="icon-btns">
                        <el-icon v-if="index === timeList.length - 1" class="add" @click.stop="addAdTime(item, index)">
                            <CirclePlus />
                        </el-icon>

                        <el-icon v-if="timeList.length > 1" class="del" @click.stop="delTime(item, index)">
                            <Delete />
                        </el-icon>
                    </div>
                </div>
            </div>

            <div class="adertising-list">
                <SearchTable v-bind="gridOptions" v-model:pager="tablePage" :loading="isLoading" :data="list"
                    class="advertising-list" @page-change="handlePageChange">
                    <template #toolbar_buttons>
                        <el-button type="primary" plain :disabled="!timeList[currentTime].activeTime?.length"
                            @click="addAdvertising">
                            添加楼盘
                        </el-button>
                    </template>

                    <template #plate="row">
                        {{ useDict('PlateType', row.row.plate) }}
                    </template>

                    <template #activeStatus="{ row }">
                        <el-switch v-model="row.activeStatus" :active-value="1" :inactive-value="0"
                            @change="switchActiveStatus(row)" />
                    </template>

                    <template #operate="{ row }">
                        <div class="operate-btns">
                            <el-button type="info" text :disabled="row.sort === 1" @click="moveItem(row, '2')">
                                上移
                            </el-button>

                            <el-button type="info" text :disabled="row.sort === tablePage.total"
                                @click="moveItem(row, '3')">
                                下移
                            </el-button>

                            <el-button type="info" text :disabled="row.sort === 1" @click="moveItem(row, '1')">
                                置顶
                            </el-button>

                            <el-button type="info" text :disabled="row.sort === tablePage.total"
                                @click="moveItem(row, '4')">
                                置底
                            </el-button>

                            <el-button type="info" text @click="editAdItem(row)">
                                编辑
                            </el-button>

                            <el-button text class="del-advertising" @click="delAdvertising(row)">
                                删除
                            </el-button>
                        </div>
                    </template>
                </SearchTable>
            </div>
        </div>
    </div>

    <el-dialog v-model="dialogVisible" :close-on-click-modal="false" :close-on-press-escape="false" :title="dialogTitle"
        :class="[adgDialogTag.SELECT_MATERIAL, adgDialogTag.ADVERTISING_CONFIG, adgDialogTag.ADD_ADVERTISING, adgDialogTag.EDIT_ADVERTISING, adgDialogTag.EDIT_ADVERTISING].includes(dialogTitle) ? 'material-select-dialog' : ''"
        :width="dialogWidth" :before-close="beforeClose">
        <template #footer>
            <div class="dialog-footer">
                <el-button v-if="dialogTitle !== adgDialogTag.SELECT_MATERIAL" @click="dialogVisible = false">
                    取消
                </el-button>

                <el-button type="primary" :loading="btnLoading" @click="advertisingSbumit(adFormRef)">
                    提交
                </el-button>
            </div>
        </template>

        <template v-if="[adgDialogTag.ADD_ADVERTISING, adgDialogTag.EDIT_ADVERTISING].includes(dialogTitle)">
            <el-form ref="adFormRef" :model="adForm" label-width="140" label-position="right">
                <el-form-item label="业务类型：" prop="plate" :rules="{
                    required: true,
                    message: '请选择业务类型',
                    trigger: 'blur',
                }">
                    <el-select v-model="adForm.plate">
                        <el-option v-for="item in PlateType" :key="item.value" :value="item.value"
                            :label="item.label" />
                    </el-select>
                </el-form-item>
                <el-form-item label="楼盘/产品名称：" prop="projectName" :rules="{
                    required: true,
                    message: '请选择',
                    trigger: 'blur',
                }">
                    <el-select v-model="adForm.projectName" filterable @change="projectChange">
                        <el-option v-for="item in projectOptions" :key="item.value" :value="item.value" :label="item.label" />
                    </el-select>
                </el-form-item>
            </el-form>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.ad-by-stages {
    display: flex;
    flex-wrap: wrap;

    .time-item {
        display: flex;
        width: 310px;
        margin-bottom: 12px;

        .ad-time-piker {
            display: flex;
            align-items: center;
            position: relative;

            >.sort {
                position: absolute;
                left: 0;
                top: 0;
                width: 30px;
                height: 32px;
                display: block;
                font-size: 16px;
                line-height: 32px;
                border-right: 1px solid #e6ebf5;
                text-align: center;
                cursor: pointer;

                &.active {
                    color: var(--el-color-primary);
                    border-right: 1px solid var(--el-color-primary);
                }
            }

            &.active {
                .el-range-editor.el-input__wrapper {
                    border: 1px solid var(--el-color-primary);
                }
            }
        }

        .el-range-editor.el-input__wrapper {
            width: 260px;
            padding-left: 40px;
        }

        .icon-btns {
            display: flex;
            align-items: center;
            margin-left: 10px;

            .el-icon {
                font-size: 18px;
                cursor: pointer;

                &.add {
                    color: var(--el-color-primary);
                    margin-right: 6px;
                }

                &.del {}
            }
        }
    }
}

.del-advertising {
    color: #da0004;
}

:deep(.vxe-table) {
    height: 528px;
    overflow: auto;
}
</style>
